//
//  UserInfoViewModel.swift
//  ShareUmbrella
//
//  Created by niupark on 2017/6/12.
//  Copyright © 2017年 share more. All rights reserved.
//

import UIKit
import RxSwift
import Alamofire
import SwiftyJSON
import YSKit

enum UserUploaderStatus {
    case uploading(progress: Double)
    case error
    case completed(imageKey: String)
}


class UserInfoViewModel: NSObject {
    static func uploader(_ parameters: [String: Any], fileName: String, image: UIImage) -> Observable<UserUploaderStatus?> {
        
        return Observable.create { observer in
            
            observer.onNext(.uploading(progress: 0.0))
            let url = HostManager.kFileHost + "/u4uapi/Index/UpdateAvatorAction"
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                if let imageData = image.ys.resetSizeToData(500) {
                    // multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "avatar.png", mimeType: "image/png")
                    multipartFormData.append(imageData, withName: "avator", fileName: fileName, mimeType: "image/png")
                }
                for (key, value) in parameters {
                    if let value = value as? String {
                        // multipartFormData.appendBodyPart(data: value.data(using: String.Encoding.utf8)!, name: key)
                        multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                    } else {
                        multipartFormData.append( "\(value)".data(using: String.Encoding.utf8)!, withName: key)
                    }
                }
            }, to: url, method: .post, encodingCompletion: { (encodingResult) in
                switch encodingResult {
                case .success(let upload, _, _):
                    // 获取上传进度
                    upload.uploadProgress(closure: { (progress) in
                        print(progress.fractionCompleted)
                        let progress = (progress.fractionCompleted) > 0.98 ? 0.99 : progress.fractionCompleted
                        observer.onNext(.uploading(progress: progress))

                    })
                    upload.responseJSON { response in
                        
                        switch response.result {
                        case .success(let value):
                            
                            let json = JSON(value)
                            guard let code = json["retcode"].int, let key = json["data"]["avatorUrl"].string  else {
                                debugPrint(value)
                                observer.onNext(.error)
                                return
                            }
                            if code == 0  {
                                debugPrint(value)
                                observer.onNext(.completed(imageKey: key))
                            }else{
                                observer.onNext(.error)
                            }
                        case .failure(let error):
                            debugPrint(error)
                            observer.onNext(.error)
                        }
                        observer.onCompleted()
                    }
                case .failure(let encodingError):
                    debugPrint(encodingError)
                    observer.onNext(.error)
                    observer.onCompleted()
                }
            })
            
            return Disposables.create()
        }
        
    }

}
